package com.atguigu.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Package com.atguigu.util
 * @Program: ssm-spring-part
 * @ClassName JDBCConnections
 * @Description[类型描述] JDBC数据库连接提供者类
 * @Author: 霍杰
 * @CreateTime 2024/11/30
 * @Version 1.0
 * @Update [序号][ 日期YYYY-MM-DD][更改人姓名][变更描述]
 **/
public class JDBCConnections {
    public DruidDataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DruidDataSource dataSource) {
        this.dataSource = dataSource;
    }

    private DruidDataSource dataSource;
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    public JDBCConnections(DruidDataSource dataSource) {
        this.dataSource = dataSource;
    }

    public JDBCConnections(){
        this.dataSource = new DruidDataSource();
        this.dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        dataSource.setUrl("jdbc:sqlserver://localhost;instanceName=MSSQLSERVER2014;databaseName=MIIP;encrypt=false");
        dataSource.setUsername("sa");
        dataSource.setPassword("d8d8g2hh8");
        dataSource.setInitialSize(10);
        dataSource.setMaxActive(20);

        //Connection connection = this.dataSource.getConnection();

    }

    public Connection getConnection()  {
        try {
            //先从ThreadLocal中获取connection
            Connection connection = threadLocal.get();
            //如果Connection为空表明是第一次获取
            if (connection == null) {
                //从连接池中获取一个connection对象
                connection = dataSource.getConnection();
                //同时保存在ThreadLocal中
                threadLocal.set(connection);
            }

            return connection;
        }
        catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void releadse(){
        try {
            Connection connection = threadLocal.get();
            if (connection != null) {
                threadLocal.remove();
                connection.setAutoCommit(true);
                connection.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }


}
